package com.wen.tian.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wen.tian.mapper.LoginMapper;
import com.wen.tian.pojo.SysUser;
import com.wen.tian.shiro.exception.UserBlockedException;
import com.wen.tian.shiro.exception.UserNotExistsException;
import com.wen.tian.shiro.exception.UserPasswordNotMatchException;
import com.wen.tian.shiro.exception.UserPasswordRetryLimitExceedException;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author tww
 * ClassName: LoginService.java、
 * createTime: 2021年01月02日 22:39:47
 **/
@Service
public class LoginService {
    private static final Logger logger = LoggerFactory.getLogger(LoginService.class);

    @Autowired
    private LoginMapper loginMapper;

    private Integer max = 5;

    @Autowired
    private CacheManager cacheManager;

    private Cache<String, AtomicInteger> loginRecordCache;

    @PostConstruct
    public void init() {
        loginRecordCache = cacheManager.getCache("loginRecordCache");
    }

    public SysUser login(String userName, String password) throws UserNotExistsException, UserBlockedException, UserPasswordRetryLimitExceedException, UserPasswordNotMatchException {
        SysUser sysUser = loginMapper.selectOne(new QueryWrapper<SysUser>()
                .eq("user_name", userName));
        if (null == sysUser) {
            throw new UserNotExistsException("用户不存在/密码错误");
        }
        if ("2".equals(sysUser.getStatus())) {
            throw new UserBlockedException("账户已停用请联系管理员");
        }

        //校验密码
        chechkPassWord(sysUser, password);

        return sysUser;
    }

    private void chechkPassWord(SysUser user, String password) throws UserPasswordRetryLimitExceedException, UserPasswordNotMatchException {
        String userName = user.getUserName();

        AtomicInteger retryCount = loginRecordCache.get(userName);
        logger.info("当前错误次数" + retryCount);
        if (retryCount == null) {
            retryCount = new AtomicInteger(0);
            loginRecordCache.put(userName, retryCount);
        }
        if (retryCount.incrementAndGet() > max) {
            throw new UserPasswordRetryLimitExceedException("密码错误" + max + "次" + "账户被锁定十分钟");
        }

        //校验用户输入密码是否正确
        if (!matches(user, password)) {
            loginRecordCache.put(userName, retryCount);
            throw new UserPasswordNotMatchException("用户不存在/密码错误");
        } else {
            //登录成功清楚登录缓存
            clearLoginRecordCache(userName);
        }

    }

    public boolean matches(SysUser user, String password) {
        return user.getPassWord().equals(password);
    }

    public void clearLoginRecordCache(String userName) {
        loginRecordCache.remove(userName);
    }
}
